package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/login")
    public Result login(@RequestBody Map map, HttpServletResponse response) {

        String telephone = (String) map.get("telephone");
        String m_code = (String) map.get("validateCode");


        //校验验证码和手机号 不为空
        if (StringUtils.isBlank(telephone) || StringUtils.isBlank(m_code))
            return new Result(false,MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);


        String r_code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        //如果验证码匹配失败
        if (!m_code.equals(r_code)) {
            //返回错误信息
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

        //验证码校验通过,校验当前用户是否已经注册
        Member member = memberService.findTelephone(telephone);


        if (member != null) {
            //说明已注册,直接登录即可
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }

        //未注册
        member = new Member();
        member.setPhoneNumber(telephone);
        member.setRegTime(new Date());
        Result result = memberService.regest(member);


        //将用户的手机号写入到cookie中,使用户登录后下次免登陆
        Cookie cookie = new Cookie("login_member_telephon", telephone);
        //设置cookie共享范围,所有子域名都可访问
        cookie.setPath("/");
        //设置cookie过期时间 为30天
        cookie.setMaxAge(60 * 60 * 24 * 30);
        //将cookie发送回浏览器本地保存
        response.addCookie(cookie);

        //将用户保存到redis中,设置30分钟不操作自动下线
        String json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone, 30 * 60, json);

        return result;
    }
}
